package net.jarang.android.saleoffline.domain.appinfo;

import net.jarang.android.saleoffline.SaleContext;
import net.jarang.android.saleoffline.domain.member.MemberDao;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.telephony.TelephonyManager;
import android.util.Log;

public class AppManager {
	private static final String PREFERENCE_NAME = "saleoffline.properties";
	private SharedPreferences preferences;
	private MemberDao memberDao;
	
    public AppManager(Context context) {
    	preferences = context.getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);
    	memberDao = new MemberDao();
    	TelephonyManager telephoneyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		String myPhoneNo = telephoneyManager.getLine1Number();
		SaleContext.myPhoneNo = myPhoneNo;
    }
    
    public Member init() {
//    	Member member = memberDao.select(SaleContext.myPhoneNo);
    	Member member = select();
    	if (member == null) {
    		member = new Member(SaleContext.myPhoneNo, null, null, false, false);
    		int id = insert(member);
    		member.setId(id);
    	}
    	return member;
    }

    public Member select() {
    	Member member = new Member();
    	member.setMemberYn(preferences.getBoolean("memberYn", false));
    	member.setLoginYn(preferences.getBoolean("loginYn", false));
		return member;
	}

	public int insert(Member member) {
    	int id = memberDao.insert(member);
    	Editor editor = preferences.edit();
    	editor.putInt("id", id);
        editor.putString("myPhoneNo", member.getPhoneNo());
        editor.putString("nickname", member.getNickname());
        editor.putBoolean("memberYn", member.getMemberYn());
        editor.putBoolean("loginYn", member.getLoginYn());
        Log.v(SaleContext.TAG, member.getMemberYn() + "");
        editor.commit();
        return id;
    }

    public boolean isMember() {
        return preferences.getBoolean("memberYn", false);
    }
    
    public boolean isLogin() {
    	return preferences.getBoolean("loginYn", false);
    }

    public void updateMemberYn(boolean isMember) {
    	memberDao.updateMemberYn(isMember);
    	Editor editor = preferences.edit();
        editor.putBoolean("memberYn", isMember);
        editor.commit();
    }

    public void updateLoginYn(boolean isLogin) {
    	Editor editor = preferences.edit();
        editor.putBoolean("loginYn", isLogin);
        editor.commit();
    }
}

